import threading
import time


class TaskRunner:
    def __init__(self):
        self.task = None
        self.timeout = None
        self.timeout_callback = None
        self.task_thread = None
        self._stop_event = threading.Event()
        self._reset_event = threading.Event()

    def start_task(self, task, timeout, timeout_callback):
        self.task = task
        self.timeout = timeout
        self.timeout_callback = timeout_callback
        if self.task_thread is None or not self.task_thread.is_alive():
            self._stop_event.clear()
            self.task_thread = threading.Thread(target=self._run_task)
            self.task_thread.start()
        else:
            self._reset_event.set()

    def _run_task(self):
        while not self._stop_event.is_set():
            self._reset_event.clear()
            end_time = time.time() + self.timeout
            while time.time() < end_time and not self._reset_event.is_set():
                time.sleep(0.1)  # 频率可以根据需要调整
            if not self._reset_event.is_set():
                self.task()
                self.timeout_callback()

    def stop_task(self):
        self._stop_event.set()
        if self.task_thread is not None:
            self.task_thread.join()


def example_task():
    print("任务正在执行...")


def timeout_feedback():
    print("任务超时！")


# 示例用法
runner = TaskRunner()

# 启动任务，超时时间为5秒
runner.start_task(example_task, 5, timeout_feedback)

# 模拟在3秒后重置任务
time.sleep(3)
runner.start_task(example_task, 5, timeout_feedback)

# 模拟在7秒后再次重置任务
time.sleep(7)
runner.start_task(example_task, 5, timeout_feedback)

# 停止任务
time.sleep(10)
runner.stop_task()

